<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>用户管理</title>
    <link rel="stylesheet" href="/static/layui/css/layui.css" media="all" />
    <script src="https://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript" src="/static/layui/layui.js"></script>
    <script type="text/javascript" src="/static/js/base.js"></script>
<body class="layui-anim layui-anim-up">
<div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>用户管理</cite>
        </a>
      </span>
</div>
<div class="x-body">

    <div class="layui-row" style="margin-bottom: 18px">
        <div class="layui-form">
            <div class="layui-input-inline">

                <div class="layui-input-inline" style="width: 150px">
                    <input class="layui-input" id="keyword01" placeholder="请输入姓名" style="width: 150px">
                </div>
                <button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
            </div>
        </div>
    </div>

    <xblock>
        <button class="layui-btn layui-btn-warm" id="add"><i class="layui-icon layui-icon-add-circle-fine"></i>新增</button>
        <!--<button class="layui-btn layui-btn-danger" id="del"><i class="layui-icon layui-icon-delete"></i>批量删除</button>-->
    </xblock>
    <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
</div>
<div id="addDivID" style="display:none">

    <form class="layui-form" id="addFormID" style="margin-top:20px">

        <!--<div class="layui-form-item">-->
            <!--<fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">-->
                <!--<legend style="font-size:16px;">基础信息</legend>-->
            <!--</fieldset>-->
        <!--</div>-->
        <div style="margin-top: 10px"></div>
        <div class="layui-form-item">
            <label for="uname" class="layui-form-label">
                <span class="x-red">*</span>用户名
            </label>
            <div class="layui-input-inline">
                <input type="text"  id="uname" name="username"  lay-verify="username"
                       autocomplete="off" class="layui-input">
            </div>
            <div id="ms" class="layui-form-mid layui-word-aux">
                <span class="x-red">*</span><span id="ums">将会成为您唯一的登入名</span>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label for="realName" class="layui-form-label">
                    <span class="x-red">*</span>真实姓名
                </label>
                <div class="layui-input-inline">
                    <input type="hidden" name="logOn" value="0">
                    <input type="text" id="realName" name="realName" lay-verify="realName"  autocomplete="off" class="layui-input">
                </div>
            </div>

        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label for="password" class="layui-form-label">
                    <span class="x-red">*</span>密码
                </label>
                <div class="layui-input-inline">
                    <input type="password" id="password" name="password"  lay-verify="password"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label for="L_repass" class="layui-form-label">
                    <span class="x-red">*</span>确认密码
                </label>
                <div class="layui-input-inline">
                    <input type="password" id="l_repass" name="repass" lay-verify="required|confirmPass"
                           autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label for="realName" class="layui-form-label">
                    <span class="x-red">*</span>邮箱
                </label>
                <div class="layui-input-inline">
                    <input type="text" id="email" name="email" lay-verify="email"  autocomplete="off" class="layui-input">
                </div>
            </div>

        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">
                <span class="x-red">*</span><span>登录方式</span>
            </label>
            <div class="layui-input-inline"  style = "width:280px;">
                <select lay-filter="type" name="type" lay-verify="required">
                    <option value="0">厂内</option>
                    <option value="1">供应商</option>

                </select>
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">角色选择</label>
            <div class="layui-input-block">
                <input th:each="roleData:${roleDataList}" type="checkbox" name="roleId"  th:title="${roleData.roleName}" th:value="${roleData.roleId}">
                <!--<input th:each="roleData:${roleDataList}"  name="roleId" type="checkbox" th:value="${roleData.roleId}" th:text="${roleData.roleName}">-->
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" id="subBtn" lay-submit lay-filter="addForm">立即提交</button>
                <button  class="layui-btn layui-btn-primary">取消</button>
            </div>
        </div>

    </form>
</div>


<div id="updateDivID" style="display:none">
    <form class="layui-form" id="updateFormID" style="margin-top:20px">
        <div style="width:100%">


            <!--<div class="layui-form-item">
                <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
                    <legend style="font-size:16px;">基础信息</legend>
                </fieldset>
            </div>-->
            <div style="margin-top: 10px"></div>
            <div class="layui-form-item">
                <label for="uname" class="layui-form-label">
                    <span class="x-red">*</span>用户名
                </label>
                <div class="layui-input-inline">
                    <input type="text"  id="unames" name="username"  lay-verify="username"
                           autocomplete="off" class="layui-input">
                </div>
                <div id="ms1" class="layui-form-mid layui-word-aux">
                    <!--<span class="x-red">*</span><span id="umss">将会成为您唯一的登入名</span>-->
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label for="realName" class="layui-form-label">
                        <span class="x-red">*</span>真实姓名
                    </label>
                    <div class="layui-input-inline">
                        <input type="hidden" name="logOn" value="0">
                        <input type="text" id="realNames" name="realName" lay-verify="realName"  autocomplete="off" class="layui-input">
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label for="realName" class="layui-form-label">
                        <span class="x-red">*</span>邮箱
                    </label>
                    <div class="layui-input-inline">
                        <input type="hidden" name="userId">
                        <input type="text" id="emails" name="email" lay-verify="email"  autocomplete="off" class="layui-input">
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <label class="layui-form-label">角色选择</label>
                <div class="layui-input-block" id="roleIdSelect"></div>
            </div>

        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" id="updateSubBtn" lay-submit lay-filter="updateForm">更新</button>
                <button  class="layui-btn layui-btn-primary">取消</button>
            </div>
        </div>
    </form>
</div>

<script type="text/html" id="toolBar">
    <a class="layui-btn layui-btn-xs  layui-btn-normal" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script>
    $(document).ready(function () {
        var time = new Date();
        var day = ("0" + time.getDate()).slice(-2);
        var month = ("0" + (time.getMonth() + 1)).slice(-2);
        var today = time.getFullYear() + "-" + (month);
        $('#dateTime').val(today);
    })

    layui.use(['table','layer','upload','form','laydate'], function(){
        var table = layui.table;
        var form=layui.form;
        var laydate = layui.laydate;
        laydate.render({
            elem: '#date1',
            value:new Date()
        });
        laydate.render({
            elem: '#date2'
        });

        laydate.render({
            elem: '#date3',
            type: 'month',
            value: new Date(),
            done:function(value, date, endDate) {
                $('#dateTime').val(value);
            }
        });

        var $ = layui.jquery, active = {
            reload:function () {
                table.reload('contentTable',{
                    method:'get'
                    ,where:{
                        'realName':$('#keyword01').val()
                    }
                    ,page: {
                        curr: 1//重新从第 1 页开始
                    }
                });
            }
        }

        table.render({
            elem: '#tableList'
            ,id:'contentTable'
            ,url: '/user/queryUserPage'
            ,toolbar: '#toolbar'
            ,where:{
                'logOn':'0'
            }
            ,cols: [
                [ //表头
                // {field: 'id',type: 'checkbox', align:'center', fixed: 'left'},
                {field:'uid', title:'序号', width: 60, type:'numbers',align:'center'}
                ,{field: 'username', title: '用户名', width: '20%'}
                ,{field: 'email', title: '邮箱', width: '20%'}
                ,{field: 'realName', title: '真实姓名', width: '20%'}
                ,{field: 'remark', title: '操作', toolbar: "#toolBar"}
            ]
            ]
            , page: true
            ,totalRow: true
            ,done : function(res, curr, count){
                $('th').css({
                    'background-color': '#3388CB', 'color': '#fff','font-weight':'bold',
                })
            }
        });



        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        $('.layui-col-md12 .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        $('.select .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        $('.layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });



        //监听工具条
        table.on('tool(tableList)', function (obj) {
            var data = obj.data;
            if (obj.event === 'detail') {
                //detail('编辑角色', 'updateRole?id=' + data.roleId, 700, 450);
            } else if (obj.event === 'del') {
                layer.confirm('确定删除角色？[<label style="color: #00AA91;">' + data.realName + '</label>]?', {
                    btn: ['确定','取消'] //按钮
                }, function(index){
                    del(data.userId)
                })

            } else if (obj.event === 'edit') {
                update('编辑用户', 'showUpdateUser?userId=' + data.userId, 540, 520);
            }
        });

        /**
         * 删除
         *
         * */
        function del(userId) {
            $.ajax({
                type: 'get',
                url: '/user/deleteUser',
                data:{'userId':userId},
                success: function (data) {
                    if (data == 1) {
                        layer.msg('删除成功',{icon: 1})
                    }else {
                        layer.msg("请联系管理员！", {icon: 2});
                    }
                    setTimeout(function(){
                        window.location.reload()
                    },1000);
                }
            })
        }

        function update(title, url, w, h) {
            if (title == null || title == '') {
                title = false;
            }
            if (url == null || url == '') {
                url = "/error/404";
            }
            if (w == null || w == '') {
                w = ($(window).width() * 0.9);
            }
            if (h == null || h == '') {
                h = ($(window).height() - 50);
            }
            layer.open({
                id: 'user-update',
                type: 1,
                area: [w + 'px', h + 'px'],
                maxmin: true,
                anim: 1,
                shade: 0.4,
                title: title,
                /***
                 * ,{field: 'username', title: '用户名', width: '20%'}
                 ,{field: 'email', title: '邮箱', width: '20%'}
                 ,{field: 'realName', title: '真实姓名', width: '20%'}
                 ]
                 */
                content: $('#updateDivID'),
                success: function(){
                    form.render();
                    $.ajax({
                        type:'get',
                        url:url,
                        success:function (data) {
                            var sysUser = JSON.parse(data);
                            //员工ID
                            $('input[name="userId"]').val(sysUser.userId);
                            //员工编号
                            $('input[name="username"]').val(sysUser.username);
                            //姓名
                            $('input[name="realName"]').val(sysUser.realName);
                            //手机号码
                            $('input[name="phoneNumber"]').val(sysUser.phoneNumber);
                            //邮箱
                            $('input[name="email"]').val(sysUser.email);

                            var sysRole = sysUser.sysRoleList;
                            $('#roleIdSelect').empty();
                            //角色
                            for (var i = 0; i < sysRole.length; i++) {
                                if (sysRole[i].selection){
                                    $('#roleIdSelect').append('<input type="checkbox"  name="roleId" value="'+sysRole[i].roleId+'" title="'+sysRole[i].roleName+'" checked>')
                                }else {
                                    $('#roleIdSelect').append('<input type="checkbox"  name="roleId" value="'+sysRole[i].roleId+'" title="'+sysRole[i].roleName+'">')
                                }
                            }
                            form.render(); //更新全部

                        }
                    })
                }
            });
        }

        function updateUser(title,url,w,h) {
            layer.open({
                id: 'user-add',
                type: 2,
                area: [w+'px',h+'px'],
                fix: false,
                btn: ['添加', '取消'],
                maxmin: true,
                shadeClose: false,
                shade: 0.4,
                title: title,
                content: url,
                yes:function(index,layero) {
                    var iframeWindow = (layero).find("iframe")[0].contentWindow;
                    var value = iframeWindow.update();
                    if (value == 0) {
                        layer.msg("请联系管理员！", {icon: 2});
                        return;
                    }
                    layer.msg("更新成功！", {icon: 1});
                    setTimeout(function(){
                        window.location.reload()
                    },1000);
                }
            });

        }


        $("#add").click(function(){
            $("#brand1").hide()
            $("#brand2").hide()

            layer.open({
                type: 1 ,				//Page层类型
                area: ['540px', '520px'] 	//宽  高
                ,title: '新增'
                ,shade: 0.6 			//遮罩透明度
                ,maxmin: true 			//允许全屏最小化
                ,anim: 1 				//0-6的动画形式，-1不开启
                ,content: $('#addDivID')
                ,success: function(){
                    //$("input[name='createDate']").val("");
                    $("input[name='wareHouseName']").val("");
                    $("textarea[name='wareHouseIp']").val("");
                    $("textarea[name='wareHousePort']").val("");
                    form.render();
                }
            });
        });



        //批量删除
        $("#del").click(function(){
            var rowData = table.checkStatus('contentTable');
            var data = rowData.data;
            var idArr = new Array();
            if(data.length == 0){

                layer.alert("请至少选择一条记录！",{icon :5})

            } else {
                for(var i=0;i < data.length;i++){
                    idArr[i] = data[i].wareHouseId;
                }
                $.ajax({
                    type:'post',
                    url:'/wareHouse/delete',
                    data:{"idArr" : idArr},
                    success:function(data){
                        layer.confirm('确定删除吗？', function(){
                            if(data > 0){
                                layer.msg('删除成功',{icon:6})
                                setTimeout(function(){
                                    location.reload();
                                },1000);
                                setTimeout(function(){
                                    window.location.reload();
                                },2000);
                            }else{
                                layer.msg('删除失败',{icon:5})
                                location.reload();
                            }
                        });
                    }
                });
            }
        });

        form.verify({

            confirmPass:function(value){
                if($('input[name=password]').val() !== value)
                    return '两次密码输入不一致！';
            },


            realName:function (value, item) {
                if(value.trim() == ''){
                    return '姓名不能为空';
                }
            },
            username:function (value, item) {
                if(value.trim() == ''){
                    return '用户名不能为空';
                }
            },


        })

        /**  data:{itemName:"12",startDate:'2019-09-20'},
         * 通用表单提交(AJAX方式),totalMoney:100,startDate:'2019-09-20',dueDate:'2019-09-20'
         */
        form.on('submit(addForm)', function () {
            var r=document.getElementsByName("roleId");
            var role=[];
            for(var i=0;i<r.length;i++){
                if(r[i].checked){
                    console.info(r[i].value);
                    role.push(r[i].value);
                }
            }

            if(role.length == 0){
                layer.msg("角色不能为空",{icon:5})
                return false;
            }

            var dataTable = $.param({'role':role}) + '&' + $('#addFormID').serialize()
            $("#subBtn").attr("disabled",true);
            $.ajax({
                type:'post',
                url:'/user/addUser',
                data:dataTable,
                cache:false,
            }).done(
                function(res) {
                    if (res > 0) {
                        layer.msg('新增成功',{icon:1})
                        setTimeout(function(){
                            location.reload();
                        },1000);
                    }else {
                        layer.msg("请联系管理员！",{icon:2})
                    }
                }
            ).fail(
                function() {
                    layer.msg('请联系管理员',{icon:2})
                    setTimeout(function(){
                        location.reload();
                    },1000);
                }
            )
            return false;
        })

        form.on('submit(updateForm)', function () {

            var r=document.getElementsByName("roleId");
            var role=[];
            for(var i=0;i<r.length;i++){
                if(r[i].checked){
                    console.info(r[i].value);
                    role.push(r[i].value);
                }
            }
            if(role.length == 0){
                layer.msg("角色不能为空",{icon:5})
                return false;
            }
            var dataTable = $.param({'role':role}) + '&' + $('#updateFormID').serialize()
            $("#subBtn").attr("disabled",true);
            $.ajax({
                type:'post',
                url:'/user/updateUser',
                data:dataTable,
                cache:false,
            }).done(
                function(res) {
                    if (res > 0) {
                        layer.msg('更新成功',{icon:6})
                        setTimeout(function(){
                            location.reload();
                        },1000);
                    }
                }
            ).fail(
                function() {
                    layer.msg('新增失败',{icon:5})
                    setTimeout(function(){
                        location.reload();
                    },1000);
                }
            )
            return false;
        })
    });
</script>
</body>

</html>
